<?php
namespace Models;

use Utils\Database;

/**
 * 路口模型类
 */
class Intersection {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * 获取所有路口列表
     */
    public function getAllIntersections() {
        $sql = "SELECT * FROM intersections ORDER BY id ASC";
        return $this->db->query($sql)->fetchAll();
    }
    
    /**
     * 获取指定路口信息
     */
    public function getIntersectionById($id) {
        $sql = "SELECT * FROM intersections WHERE id = ?";
        return $this->db->query($sql, [$id])->fetch();
    }
    
    /**
     * 添加新路口
     */
    public function addIntersection($data) {
        $sql = "INSERT INTO intersections (name, longitude, latitude, controller_type, status) 
                VALUES (?, ?, ?, ?, ?)";
        return $this->db->query($sql, [
            $data['name'],
            $data['longitude'],
            $data['latitude'],
            $data['controller_type'],
            $data['status'] ?? 1
        ]);
    }
    
    /**
     * 更新路口信息
     */
    public function updateIntersection($id, $data) {
        $sql = "UPDATE intersections SET 
                name = ?, 
                longitude = ?, 
                latitude = ?, 
                controller_type = ?, 
                status = ?,
                updated_at = CURRENT_TIMESTAMP 
                WHERE id = ?";
        return $this->db->query($sql, [
            $data['name'],
            $data['longitude'],
            $data['latitude'],
            $data['controller_type'],
            $data['status'],
            $id
        ]);
    }
    
    /**
     * 删除路口
     */
    public function deleteIntersection($id) {
        $sql = "DELETE FROM intersections WHERE id = ?";
        return $this->db->query($sql, [$id]);
    }
    
    /**
     * 获取活跃路口数量
     */
    public function getActiveIntersectionsCount() {
        $sql = "SELECT COUNT(*) as count FROM intersections WHERE status = 1";
        return $this->db->query($sql)->fetch()['count'];
    }
    
    /**
     * 获取指定区域内的路口
     */
    public function getIntersectionsInArea($minLng, $maxLng, $minLat, $maxLat) {
        $sql = "SELECT * FROM intersections 
                WHERE longitude BETWEEN ? AND ? 
                AND latitude BETWEEN ? AND ?";
        return $this->db->query($sql, [$minLng, $maxLng, $minLat, $maxLat])->fetchAll();
    }
} 